<?php
/**
 * User: zhangligang
 * Email: tzhang2450@163.com
 * Date: 2018/11/20
 * Time: 03:11
 */

namespace App\Http\Services;


use App\Http\Models\Mark;
use App\Http\Models\User;
use Symfony\Component\Finder\Exception\AccessDeniedException;

class MarkService
{

    public static function getListByWorkId($workId)
    {
        $marks = Mark::where('work_id', $workId)->where('is_del', 0)->get();
        $data = [];
        foreach ($marks as $mark) {
            $user = User::where('id', $mark->teacher_id)->first();
            $data[] = [
                'id' => $mark->id,
                'score' => $mark->score,
                'user_id' => $mark->teacher_id,
                'realname' => $user->realname
            ];
        }
        return $data;
    }

    public static function save($data)
    {
        $mark = Mark::where('work_id', $data['work_id'])->where('teacher_id', $data['teacher_id'])->where('is_del', 0)->first();
        if ($mark) {
            throw new AccessDeniedException('您已为该作品评分', 4032);
        }
        $mark = new Mark();
        $mark->work_id = $data['work_id'];
        $mark->teacher_id = $data['teacher_id'];
        $mark->score = $data['score'];
        $mark->is_del = 0;
        $now = date('Y-m-d H:i:s', time());
        $mark->created_at = $now;
        $mark->updated_at = $now;
        $mark->save();
    }

    public static function delete($id)
    {
        $mark = Mark::where('id', $id)->where('is_del', 0)->first();
        if (!$mark) {
            throw new AccessDeniedException('评分不存在或已删除', 4032);
        }
        $mark->is_del = 1;
        $mark->updated_at = date('Y-m-d H:i:s', time());
        $mark->save();
    }
}